from pathlib import Path
import re
import os

os.chdir(Path(__file__).parent)


def build_svg_handler():
    m_get_except_svg_tag_pat = re.compile(r"<svg.*?>(.*?)</svg>", re.DOTALL)

    def remove_svg_tag(html: str):

        # 使用捕获组提取svg标签中的内容
        result = m_get_except_svg_tag_pat.search(html)

        if result:
            svg_content = result.group(1)
            return svg_content

        return html

    return remove_svg_tag


def build_file_creator(template_path: str, dir="."):
    from jinja2 import Environment, FileSystemLoader

    env = Environment(loader=FileSystemLoader(dir))
    template = env.get_template(template_path)

    var_infos = []

    def add_info(var: str, svg: str):
        info = {"var": f"md_{var}", "svg_path": svg}
        var_infos.append(info)

    def create_file(file="material_icons.py"):
        code = template.render(var_infos=var_infos)

        result_dir = Path(".result")
        if not result_dir.exists():
            os.makedirs(result_dir.name)

        target_path = result_dir / Path(file)
        target_path.write_text(code, encoding="utf8")

    return add_info, create_file


# 路径修改成本地
# 下载地址：https://github.com/material-icons/material-icons/tree/master/svg
src_folders = list(Path(r"E:\working\github\material-icons\svg").glob("*"))

names = [f.name for f in src_folders]
target_files = [f / "round.svg" for f in src_folders]

remove_svg_tag = build_svg_handler()
add_info, create_file = build_file_creator("copy_material_icons_svg.template")


source = zip(names, target_files)

for name, target in source:
    svg_paths = remove_svg_tag(target.read_text())
    add_info(name, svg_paths)

create_file("material_icons.py")
